# 代码雨字符单元示例（基于搜索结果:cite[2]修改）
# 一个极简的 Pygame 结构框架:cite[6]
import pygame
import random
pygame.init()

SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
FONT_SIZE = 20

class CodeRainChar:
    def __init__(self, x, y, speed, char=None):
        self.x = x
        self.y = y
        self.speed = speed
        self.char = char if char else random.choice('0101010101ITonyABCDEFGHIJKLMNOPQRSTUVWXYZ@#$%^&*()')
        # 可以根据位置或速度设置颜色
        self.color = (0, min(255, 50 + int(self.speed * 20)), 0) # 绿色渐变

    def update(self):
        self.y += self.speed
        if self.y > SCREEN_HEIGHT:
            self.y = 0
            self.char = random.choice('0101010101ITonyABCDEFGHIJKLMNOPQRSTUVWXYZ@#$%^&*()')
            self.speed = random.randint(10, 25) # 随机速度:cite[2]

    def draw(self, surface, font):
        text_surface = font.render(self.char, True, self.color)
        surface.blit(text_surface, (self.x, self.y))

# 初始化多列
rain_chars = []
for x in range(0, SCREEN_WIDTH, FONT_SIZE): # 每隔 FONT_SIZE 像素一列
    initial_y = random.randint(-100, 0) # 初始位置随机在屏幕上方
    rain_chars.append(CodeRainChar(x, initial_y, random.randint(10, 25)))


screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Algorithm Visualization")
clock = pygame.time.Clock()
FPS = 1200

running = True
while running:
    # 1. 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # 处理其他事件，如按键

    # 2. 更新游戏状态/算法逻辑
    # (例如：更新对象位置、运行算法的一步)
    # for rain_char in rain_chars:
    #     rain_char.update()
    #     rain_char.draw(screen, pygame.font.SysFont(None, FONT_SIZE))

    # 3. 绘制
    # screen.fill((0, 0, 0))  # 用黑色清除屏幕
    # 绘制所有对象、图形、文字
    # (例如：绘制网格、路径、条形图、分形)

    for rain_char in rain_chars:
        rain_char.update()

        # 在屏幕上绘制雨滴字符
        rain_char.draw(screen, pygame.font.SysFont(None, FONT_SIZE))
        # 延迟10毫秒，控制动画速度
        # pygame.time.delay(10)
        # 更新整个显示 surface
        pygame.display.flip()
        # 再次延迟10毫秒，确保动画流畅性
        # pygame.time.delay(10)


    # 4. 更新显示
    pygame.display.update()
    clock.tick(FPS)  # 控制帧率

pygame.quit()